//动态详情
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database() //数据库
const $ = db.command.aggregate
const _ = db.command
//获取动态详情
const dynamicDetail = async function (params) {
  const wxContext = cloud.getWXContext()
  const resultData = await db.collection('dynamic').aggregate().match({
      _id: params.dynamicId
    })
    .lookup({
      from: "user",
      let: {
        openid: "$_openid"
      },
      pipeline: $.pipeline().match(_.expr($.eq(['$_openid', '$$openid']))).project({
        _id: 0,
        nickName: 1,
        headPortrait: 1
      }).done(),
      as: "userInfo"
    })
    .replaceRoot({
      newRoot: $.mergeObjects([$.arrayElemAt(['$userInfo', 0]), '$$ROOT'])
    })
    .project({
      userInfo: 0,
      _openid: 0
    })
    .end()
  //获取当前动态的评论
  const commentResult = await db.collection('dynamicComment').aggregate().match({
      dynamicId: params.dynamicId
    }).lookup({
      from: "user",
      let: {
        openid: "$_openid"
      },
      pipeline: $.pipeline().match(_.expr($.eq(['$_openid', '$$openid']))).project({
        _id: 0,
        nickName: 1,
        headPortrait: 1
      }).done(),
      as: "userInfo"
    })
    .replaceRoot({
      newRoot: $.mergeObjects([$.arrayElemAt(['$userInfo', 0]), '$$ROOT'])
    })
    .project({
      userInfo: 0,
      _openid: 0
    }).sort({
      createTime: -1
    })
    .end()
  //点赞数
  const endorseResult = await db.collection('dynamicEndorse').where({
    dynamicId:params.dynamicId
  }).get()
  //本人是否点赞
  const isEndorse = await db.collection('dynamicEndorse').where({
    dynamicId:params.dynamicId,
    _openid:wxContext.OPENID
  }).get()
  if (resultData.list) {
    let data = resultData.list[0]
    data.endorseCount = endorseResult.data.length
    data.isEndorse = isEndorse.data.length
    data.comments = commentResult.list
    return data
  }

}
module.exports = dynamicDetail